package org.fly.filter;

import org.fly.bean.Supplier;
import org.fly.contants.WebConstant;
import org.fly.utils.CacheUtil;
import org.fly.utils.UserContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by rongzhao.zhu on 2018/2/16.
 */
public class SupplierLoginFilter extends LoginFilter{
    /**
     * 通过cookie获取用户信息
     * @param request
     * @return
     */
    protected Supplier getUser(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if(cookies ==null){
            return null;
        }
        Map<String,String> cookieMap = cookie2map(cookies);
        String token = cookieMap.get(WebConstant.cookie_token);
        Supplier user = CacheUtil.getSupplierByKey(token);
        if(user != null ){
            Map<String,String> storedCookie = user.getCookieMap();
            boolean allMatch = storedCookie.entrySet().stream().map(e->e.getValue().equals(cookieMap.get(e.getKey()))).
                    reduce(true,(a,b)->a&&b);
            if(!allMatch){
                return null;
            }else {
                return user;
            }
        }
        return null;
    }

    /**
     * 验证通过
     * @param request
     * @param response
     */
    protected  void onLogin( HttpServletRequest request,HttpServletResponse response,Supplier supplier){
        UserContext.setUser(supplier);
    }

    /**
     * 登录验证失败
     * @param request
     * @param response
     */
    protected void onNoLogin(HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.sendRedirect(getLoginUri());
    }





    public List<String> getExcludeUri() {
        return excludeUri;
    }

    public void setExcludeUri(List<String> excludeUri) {
        this.excludeUri = excludeUri;
    }

    public String getLoginUri() {
        return WebConstant.supplierLoginUrl;
    }



    private void onFinal() {
        UserContext.release();
    }
}
